import { defineStore } from 'pinia'
import { initData, getYearWeek } from '@/utils/common/dataCountStore'

export interface Group {
  baseDate: number
  count: number[]
}

interface DataCountState {
  [key: number]: Group[]
}

const useDataCountStore = defineStore('dataCount', {
  state: (): DataCountState => {
    return {}
  },

  actions: {
    /**
     * @desc 添加空统计表
     */
    addGroup(year: number = new Date().getFullYear()) {
      if (this.$state[year] === undefined) {
        this.$state[year] = initData(year)
      }
      this.updataLocalStorage()
    },

    /**
     * @desc 添加记录
     * @param time 创建时间
     */
    updataCount(time: Date) {
      this.addGroup()
      this.$state[time.getFullYear()][getYearWeek(time)].count[time.getDay()]++
      this.updataLocalStorage()
    },

    /**
     * @desc persist没有起作用，手动存储
     */
    updataLocalStorage() {
      localStorage.setItem('datacount', JSON.stringify(this.$state))
    }
  },

  persist: {
    key: 'datacount'
  }
})

export { useDataCountStore }
